
package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Holds;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.process.FinishedGoods;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.sales.SalesOrder;
import com.scalar.chiptrack.sales.SalesOrderHold;
import com.scalar.chiptrack.sales.SalesOrderHelper;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewSalesOrderDAO;
import com.scalar.chiptrack.sales.dao.SalesDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.forms.SalesHoldForm;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.StringUtils;


/**
 * Implementation of <strong>Action</strong> that gives customers list,
 * search with customer name, create sales order
 *
 * @author Kesava Kumar Achanala
 * @version $Revision: 1.14 $ $Date: 2008/11/10 12:45:19 $
 */

public final class SalesOrderHoldAction extends ChipTrackAction
{

    private static final String ACTION_NAME = "/salesHold.do";

    public ActionForward execute ( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
    {
        SalesHoldForm subform   = ( SalesHoldForm ) form;
        String action           = request.getParameter ( "action" );
        String isSampleStr      = request.getParameter ( "isSample" );
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        if ( user == null )
        {
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + "isSample="+request.getParameter("isSample") );
            return ( mapping.findForward ( "login" ) );
        }
        HashMap errors = new HashMap ();
        HashMap info = new LinkedHashMap ();

        int isSample = 1; //default set to salesOrder
        if ( isSampleStr != null && isSampleStr.length () != 0 )
        {
            try
            {
                isSample = Integer.parseInt ( isSampleStr );
            }
            catch ( NumberFormatException ignore ) { isSample = 1; }
        }

        if ( action == null )
        {
            request.setAttribute ( "customersList", CustomerDAO.getAllCustomerNames (isSample) );
            request.setAttribute ( "showList", "FALSE" );
            request.setAttribute ( "productList", loadManufacturingProducts( isSample ) );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );
            request.setAttribute ( "salesOrdersList", SalesOrderDAO.loadAllSalesOrderIds(isSample, "HoldSalesOrders" ));
            request.setAttribute ( "posList", SalesOrderDAO.loadAllCustomerPOs(isSample, "HoldSalesOrders"));


            return ( mapping.findForward ( "salesHold" ) );
        }
        else if ( "SalesHoldReleaseSearch".equals ( action ) )
        {
            //This block will clear the form contents and display an empty form for searching orders
            subform.setProductName ( null );
            subform.setCustomerId ( 0 );
            subform.setCustomerPO ( "" );
            subform.setYear ( Integer.toString ( Calendar.getInstance ().get ( Calendar.YEAR ) ) );
            request.setAttribute ( "customersList", CustomerDAO.getAllCustomerNames (isSample) );
            request.setAttribute ( "showList", "FALSE" );
            request.setAttribute ( "productList", loadManufacturingProducts( isSample ) );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );
            request.setAttribute ( "salesOrdersList", SalesOrderDAO.loadAllSalesOrderIds(isSample, "HoldSalesOrders" ));
            request.setAttribute ( "posList", SalesOrderDAO.loadAllCustomerPOs(isSample, "HoldSalesOrders"));

            return ( mapping.findForward ( "salesHold" ) );
        }
        else if ( "loadSalesOrders".equals ( action ) )
        {
            session.removeAttribute ( "ViewOrderRequest" );
            session.setAttribute ( "SalesOrderHoldReleaseRequest", "true" );
            int year = 0;
            String bookingYear = request.getParameter ( "year" );
            if ( ( bookingYear != null ) && ( bookingYear.trim ().length () != 0 ) )
            {
                try
                {
                    year = Integer.parseInt ( bookingYear );
                }
                catch ( NumberFormatException nfe )
                {
                    year = 0;
                }
            }
            if ( isSampleStr != null && isSampleStr.length () != 0 )
            {
                try
                {
                    isSample = Integer.parseInt ( isSampleStr );
                }
                catch ( NumberFormatException nfe )
                {
                    errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_GETTING_DATA );
                    errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                    session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Load Data " );
                    session.setAttribute ( SessionKeys.ERROR_REPORT, nfe );
                }
            }
            Holds hold = loadCriteriaAndValues ( request );
            ArrayList list = hold.load ();
            if ( list.size () == 0 )
            {
                errors.put ( ERROR_HOLD_RELEASE_SALES_ORDER_NOT_FOUND, null );
                if ( !errors.isEmpty () )
                {
                    request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
                }
            }
            else
            {
                request.setAttribute ( "showList", "TRUE" );
            }
            if ( !errors.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
            }
            
            request.setAttribute ( "lineItemList", list );
            request.setAttribute ( "customersList", CustomerDAO.getAllCustomerNames (isSample) );

            if ( user.isActionAllowed ( Functionality.SALES_HOLDS_RELEASE, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }

            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );

            request.setAttribute ( "productList", loadManufacturingProducts( isSample ) );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );
            request.setAttribute ( "salesOrdersList", SalesOrderDAO.loadAllSalesOrderIds(isSample, "HoldSalesOrders" ));
            request.setAttribute ( "posList", SalesOrderDAO.loadAllCustomerPOs(isSample, "HoldSalesOrders"));

            return ( mapping.findForward ( "salesHold" ) );
        }
        else if ( "loadHoldSalesOrders".equals ( action ) )
        {
            Holds hold = loadCriteriaAndValues ( request );
            ArrayList list = hold.load ();
            if ( list.size () == 0 )
            {
                errors.put ( ERROR_SALES_ORDER_NOT_FOUND, null );
            }
            else
            {
                request.setAttribute ( "showList", "TRUE" );
            }

            if ( !errors.isEmpty () )
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );

            if( list != null )
            {
                 NewSalesOrderDAO.loadCustomerPartNumbersForSearch( null, list);
            }
            request.setAttribute ( "lineItemList", list );
            request.setAttribute ( "customersList", CustomerDAO.getAllCustomerNames (isSample) );
            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );
            request.setAttribute ( "productList", loadManufacturingProducts( isSample ) );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );

            subform.setAction ( action );

            return ( mapping.findForward ( "salesList" ) );
        }
        else if ( "loadReleaseSalesOrders".equals ( action ) )
        {
            Holds hold = loadCriteriaAndValues ( request );
            hold.setLoadHoldOrders ( true ); //For loading only holded orders for releasing

            ArrayList list = hold.load ();
            if ( list.size () == 0 )
            {
                errors.put ( ERROR_SALES_ORDER_NOT_FOUND, null );
            }
            else
            {
                request.setAttribute ( "showList", "TRUE" );
            }
            if ( !errors.isEmpty () )
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );

            if( list != null )
            {
                 NewSalesOrderDAO.loadCustomerPartNumbersForSearch( null, list);
            }
            request.setAttribute ( "lineItemList", list );
            request.setAttribute ( "customersList", CustomerDAO.getAllCustomerNames (isSample) );

            request.setAttribute ( "marketingReasonCodes", SalesDAO.loadMarketingReasonCodes () );
            request.setAttribute ( "salesReasonCodes", SalesDAO.loadSalesReasonCodes () );
            request.setAttribute ( "financeReasonCodes", SalesDAO.loadFinanceReasonCodes () );
            request.setAttribute ( "opsReasonCodes", SalesDAO.loadOpsReasonCodes () );

            request.setAttribute ( "productList", loadManufacturingProducts( isSample ) );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );

            subform.setAction ( action );

            return ( mapping.findForward ( "salesList" ) );
        }
        else if ( "holdAllSalesOrders".equals ( action ) )
        {
            Holds hold = loadCriteriaAndValues ( request );
            errors.put ( "Hold", "Successfully" );
            request.setAttribute ( SessionKeys.MESSAGES, errors );
            request.setAttribute ( "productList", loadManufacturingProducts( isSample ) );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );

            hold.hold ( user );
        }
        else if ( "holdSelectedOrders".equals ( action ) )
        {
            Holds hold = loadCriteriaAndValues ( request );
            errors.put ( "Hold", "Successfully" );
            request.setAttribute ( SessionKeys.MESSAGES, errors );
            request.setAttribute ( "productList", loadManufacturingProducts( isSample ) );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );

            hold.hold ( getSelectedLineItems ( request ), user );
        }
        else if ( "releaseSalesOrders".equals ( action ) )
        {
            Holds hold = loadCriteriaAndValues ( request );
            errors.put ( "Release", "Successfully" );
            request.setAttribute ( SessionKeys.MESSAGES, errors );
            request.setAttribute ( "productList", loadManufacturingProducts( isSample ) );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );

            //release the selected lineItem Ids
            hold.release ( user );
        }
        else if ( "releaseSelectedOrders".equals ( action ) )
        {
            Holds hold = loadCriteriaAndValues ( request );
            errors.put ( "Release", "Successfully" );
            request.setAttribute ( SessionKeys.MESSAGES, errors );
            request.setAttribute ( "productList", loadManufacturingProducts( isSample ) );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );

            //hold the selected lineItem Ids
            hold.release ( getSelectedLineItems ( request ), user );
        }
        else if ( "saveSelectedOrders".equals ( action ) )
        {
            Iterator list = getAllSelectedLineItems ( request );
            Iterator cntList = getAllSelectedLineItems ( request );
            int count = 0;
            int salesOrder_Id = -1;
            while ( cntList.hasNext () )
            {
                Object lengthobj = cntList.next ();
                count++;
            }

            int i = 0;
            String[] marketingHolds = new String[count];
            String[] financeHolds = new String[count];
            String[] operationsHolds = new String[count];
            String[] salesHolds = new String[count];
            String[] lineItemId = new String[count];
            String[] salesOrderId = new String[count];
            LineItem item = new LineItem ();
            while ( list.hasNext () )
            {
                item = ( LineItem ) list.next ();
                lineItemId[i] = "" + item.getLineItemId ();
                salesOrderId[i] = "" + item.getSalesOrderId ();
                salesOrder_Id = item.getSalesOrderId ();
                marketingHolds[i] = item.getMarketingHold ();
                financeHolds[i] = item.getFinanceHold ();
                operationsHolds[i] = item.getOperationsHold ();
                salesHolds[i] = item.getSalesHold ();
                i++;
            }
            DBTransaction dbTransaction = null;

            Holds hold = loadCriteriaAndValues ( request );
            info.put ( "Holds/Release Saved", "Successfully" );

            HashMap singleAction = SalesDAO.loadActionsPeformed ( dbTransaction, lineItemId, marketingHolds, financeHolds, operationsHolds, salesHolds, "" );
            HashMap changeSummaryMap = SalesDAO.loadActionsPeformedSummary ( dbTransaction, lineItemId, marketingHolds, financeHolds, operationsHolds, salesHolds, salesOrderId );

            //For storing the sales orders which are not approved
            Object[] alarmsToBeSent = ( changeSummaryMap.keySet () ).toArray ();
            ArrayList notApprovedSalesOrder = new ArrayList ();
            for ( int tempCount = 0; tempCount < alarmsToBeSent.length; tempCount++ )
            {
                if ( SalesOrderDAO.isSalesOrderApproved ( Integer.parseInt ( ( String ) alarmsToBeSent[tempCount] ) ) == false )
                {
                    notApprovedSalesOrder.add ( salesOrderId[tempCount] );
                }
            }

            int changeActionCount = singleAction.size ();
            int salesOrderCount = 0;
            String actionChange = new String ();
            HashMap cancelledLineitems = new HashMap ();
            HashMap remainedLineitems = new HashMap ();
            HashMap newactions = new HashMap ();
            HashMap oldactions = new HashMap ();
            String actionChanged = new String ();
            int newActionCount = 0;
            int newsalesOrderCount = 0;
            int oldsalesOrderCount = 0;
            Object SalesOrdersChanged[] = ( singleAction.keySet () ).toArray ();

            oldactions = SalesDAO.loadAllActionValue ( dbTransaction, salesOrderId );
            Object oldSalesOrdersChanged[] = ( oldactions.keySet () ).toArray ();
            int oldActionCount = oldactions.size ();
            String oldSalesTax[] = new String[oldActionCount];
            String oldSalesState[] = new String[oldActionCount];
            int oldstateOffset = 0;
            int oldtotallength = 0;
            String oldactionChange[] = new String[oldActionCount];
            while ( oldsalesOrderCount < oldActionCount )
            {
                oldactionChange[oldsalesOrderCount] = ( String ) oldactions.get ( oldSalesOrdersChanged[oldsalesOrderCount] );
                oldstateOffset = oldactionChange[oldsalesOrderCount].indexOf ( "@@@" );
                oldtotallength = oldactionChange[oldsalesOrderCount].length ();
                oldSalesState[oldsalesOrderCount] = oldactionChange[oldsalesOrderCount].substring ( 0, oldstateOffset );
                oldSalesTax[oldsalesOrderCount] = oldactionChange[oldsalesOrderCount].substring ( oldstateOffset + 3, oldtotallength );
                oldsalesOrderCount++;
            }
            hold.save ( getAllSelectedLineItems ( request ), user, ( String ) request.getParameter ( "comments" ) );

            cancelledLineitems = SalesDAO.loadAllCancelledLineitems ( dbTransaction, lineItemId );
            remainedLineitems = SalesDAO.loadAllRemainedLineitems ( dbTransaction, lineItemId );

            Object cancelledLineitemsChanged[] = ( cancelledLineitems.keySet () ).toArray ();
            int numberOflineitems = cancelledLineitemsChanged.length;
            Object remainedLineitemsChanged[] = ( remainedLineitems.keySet () ).toArray ();
            int restOflineitems = remainedLineitemsChanged.length;
            String[] tempsalesIds = new String[numberOflineitems];
            String[] tempsalesIds1 = new String[numberOflineitems];
            ArrayList lineItemIds = new ArrayList ();
            boolean flag = false;
            int totalCount = 0;
            int totalCount1 = 0;

            if ( cancelledLineitems != null && numberOflineitems != 0 )
            {
                if ( remainedLineitems != null && restOflineitems != 0 )
                {

                    for ( i = 0; i < restOflineitems; i++ )
                    {
                        if ( cancelledLineitems.containsKey ( remainedLineitemsChanged[i] ) )
                        {
                            flag = true;
                            if ( totalCount < 1 && totalCount1 < 1 )
                            {
                                for ( int j = 0; j < numberOflineitems; j++ )
                                {
                                    actionChanged = "";
                                    lineItemIds = ( ArrayList ) cancelledLineitems.get ( cancelledLineitemsChanged[j] );
                                    tempsalesIds[j] = ( String ) cancelledLineitemsChanged[j];
                                    if ( lineItemIds.size () > 1 )
                                        actionChanged = actionChanged + "<br> Hence the above " + lineItemIds.size () + " Lineitems are Cancelled";
                                    else
                                        actionChanged = actionChanged + "<br> Hence the above  Lineitem is Cancelled";
                                    newactions = SalesDAO.loadAllActionValue ( dbTransaction, salesOrderId );

                                    if ( singleAction.containsKey ( tempsalesIds[j] ) )
                                    {
                                        actionChange = ( String ) singleAction.get ( SalesOrdersChanged[j] );
                                    }
                                    actionChange = actionChange + actionChanged;
                                    SalesDAO.updateSalesAuditTrail ( null, Integer.parseInt ( tempsalesIds[j] ), user.getUserId (), actionChange, "" );

                                } //for
                                totalCount++;
                                totalCount1 = 1;
                            }//if(totalCount <1 )
                        } //if
                        else
                        {
                            if ( flag == false )
                            {
                                flag = true;
                                if ( totalCount1 < 1 )
                                {
                                    for ( int j = 0; j < numberOflineitems; j++ )
                                    {
                                        actionChanged = "";
                                        lineItemIds = ( ArrayList ) cancelledLineitems.get ( cancelledLineitemsChanged[j] );
                                        tempsalesIds1[j] = ( String ) cancelledLineitemsChanged[j];
                                        if ( lineItemIds.size () > 1 )
                                            actionChanged = actionChanged + "<br> Hence the above " + lineItemIds.size () + " Lineitems are Cancelled";
                                        else
                                            actionChanged = actionChanged + "<br> Hence the above  Lineitem is Cancelled";
                                        newactions = SalesDAO.loadAllActionValue ( dbTransaction, salesOrderId );

                                        if ( singleAction.containsKey ( tempsalesIds1[j] ) )
                                        {
                                            actionChange = ( String ) singleAction.get ( tempsalesIds1[j] );
                                        }
                                        actionChange = actionChange + actionChanged;
                                        SalesDAO.updateSalesAuditTrail ( null, Integer.parseInt ( tempsalesIds1[j] ), user.getUserId (), actionChange, "" );
                                    } //for
                                    totalCount1++;
                                }
                            } //else if

                            if ( flag == true )
                            {
                                String actionChange1 = "";
                                actionChange1 = ( String ) singleAction.get ( SalesOrdersChanged[i] );
                                SalesDAO.updateSalesAuditTrail ( null, Integer.parseInt ( ( String ) remainedLineitemsChanged[i] ), user.getUserId (), actionChange1, "" );
                            }
                        }
                    } //for
                } //ifif(remainedLineitems != null)
                else if ( restOflineitems == 0 )
                {
                    for ( int j = 0; j < numberOflineitems; j++ )
                    {
                        actionChanged = "";
                        lineItemIds = ( ArrayList ) cancelledLineitems.get ( cancelledLineitemsChanged[j] );
                        tempsalesIds[j] = ( String ) cancelledLineitemsChanged[j];
                        if ( lineItemIds.size () > 1 )
                            actionChanged = actionChanged + "<br> Hence the above " + lineItemIds.size () + " Lineitems are Cancelled";
                        else
                            actionChanged = actionChanged + "<br> Hence the above  Lineitem is Cancelled";
                        newactions = SalesDAO.loadAllActionValue ( dbTransaction, salesOrderId );

                        if ( singleAction.containsKey ( tempsalesIds[j] ) )
                        {
                            actionChange = ( String ) singleAction.get ( SalesOrdersChanged[j] );
                        }
                        actionChange = actionChange + actionChanged;
                        SalesDAO.updateSalesAuditTrail ( null, Integer.parseInt ( tempsalesIds[j] ), user.getUserId (), actionChange, "" );
                    }
                }
            }
            else
            {
                String actionChange2 = new String ();
                while ( salesOrderCount < changeActionCount )
                {
                    actionChange2 = ( String ) singleAction.get ( SalesOrdersChanged[salesOrderCount] );
                    SalesDAO.updateSalesAuditTrail ( null, Integer.parseInt ( ( String ) SalesOrdersChanged[salesOrderCount] ), user.getUserId (), actionChange2, "" );
                    salesOrderCount++;
                }
            }
            Object newSalesOrdersChanged[] = ( newactions.keySet () ).toArray ();
            newActionCount = newactions.size ();
            String newSalesTax[] = new String[newActionCount];
            String newSalesState[] = new String[newActionCount];
            int stateOffset = 0;
            int totallength = 0;
            String finalActionchanged[] = new String[newActionCount];
            String newactionChange[] = new String[newActionCount];

            while ( newsalesOrderCount < newActionCount )
            {
                newactionChange[newsalesOrderCount] = ( String ) newactions.get ( newSalesOrdersChanged[newsalesOrderCount] );
                stateOffset = newactionChange[newsalesOrderCount].indexOf ( "@@@" );
                totallength = newactionChange[newsalesOrderCount].length ();
                newSalesState[newsalesOrderCount] = newactionChange[newsalesOrderCount].substring ( 0, stateOffset );
                newSalesTax[newsalesOrderCount] = newactionChange[newsalesOrderCount].substring ( stateOffset + 3, totallength );
                newsalesOrderCount++;
            }

            for ( int j = 0; j < newActionCount; j++ )
            {
                if ( !newSalesState[j].equals ( oldSalesState[j] ) )
                {
                    finalActionchanged[j] = "Sub Total is changed from <b><I>" + oldSalesState[j] + "</I></b>  to  <b><I>" + newSalesState[j] + "</I></b>";
                }
                if ( !newSalesTax[j].equals ( oldSalesTax[j] ) )
                {
                    if ( finalActionchanged[j] == null ) finalActionchanged[j] = "";
                    finalActionchanged[j] = finalActionchanged[j] + "<br> Sales Tax is changed from <b><I>" + oldSalesTax[j] + "</I></b>  to  <b><I>" + newSalesTax[j] + "</I></b>";
                }

                if ( finalActionchanged[j] != null )
                    SalesDAO.updateSalesAuditTrail ( null, Integer.parseInt ( ( String ) SalesOrdersChanged[j] ), user.getUserId (), finalActionchanged[j], "" );
            }
            //For sending the notifications abt all the sales orders whose line items have been modiifed
            try
            {
                for ( int j = 0; j < alarmsToBeSent.length; j++ )
                {
                    SalesDAO.updateAlarmAndSendMailWithChangeSummary ( "", Integer.parseInt ( ( String ) alarmsToBeSent[j] ), true, user, ( ( StringBuffer ) changeSummaryMap.get ( alarmsToBeSent[j] ) ).toString () );

                    SalesOrderHelper.notifyApprovedSalesOrderInfo ( Integer.parseInt ( ( String ) alarmsToBeSent[j] ) );
                    //notifyFinanceReasonCode ( Integer.parseInt ( ( String ) alarmsToBeSent[j] ) );
                }
                /*for ( int j = 0; j < notApprovedSalesOrder.size (); j++ )
                {
                    notifyApprovedSalesOrderInfo ( Integer.parseInt ( ( String ) notApprovedSalesOrder.get ( j ) ) );
                }*/
                info.put ( "Email ", " has been sent to all approvers" );
            }
            catch ( Exception ex )
            {
                ex.printStackTrace ();
                errors.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SENDING_MAILS_TO_APPROVERS );
            }
            request.setAttribute ( "productList", loadManufacturingProducts( isSample ) );
            request.setAttribute ( "years", SalesOrderDAO.getYearList () );
        }

        request.setAttribute ( SessionKeys.MESSAGES, info );
        return ( mapping.findForward ( "successSalesHoldReleaseSearch" ) );
    }

    private static Holds loadCriteriaAndValues ( HttpServletRequest request ) throws ScalarException
    {
        //For searching using all the three criteria (SalesOrderNo,customer,product)
        Holds hold = new SalesOrderHold ();
        String customerPO = request.getParameter ( "customerPO" );
        String productName = request.getParameter ( "productName" );
        String customerId = request.getParameter ( "customerId" );
        String year = request.getParameter ( "year" );
        String isSample = request.getParameter("isSample");
        if ( productName == null ) productName = "";
        if ( customerId == null ) customerId = "";
        if ( customerPO == null ) customerPO = "";
        if ( customerPO.trim().length () != 0 && !("0".equalsIgnoreCase(customerPO.trim())))
        {
                hold.setParameter ( "CustomerPO", customerPO.trim () );
                hold.setParameter ( "isSample", isSample);
                if ( productName.equals ( "" ) && customerId.equals ( "" ) && year.equals ( "" ) )
                {
                    hold.setCriteria ( Holds.SALES_ORDER_BY_CUSOTMER_PO );
                }
                else
                {
                    hold.setCriteria ( Holds.SALES_ORDER_BY_SALESORDERNO_PRODUCT_CUSTOMER_YEAR );
                    hold.setParameter ( "CustomerID", customerId.trim () );
                    hold.setParameter ( "ProductID", productName );
                    hold.setParameter ( "Year", year );
                }
         }
        else
        {
            hold.setCriteria ( Holds.SALES_ORDER_BY_CUSTOMER_PRODUCT_YEAR );
            hold.setParameter ( "isSample", isSample);
            hold.setParameter ( "CustomerID", request.getParameter ( "customerId" ) );
            hold.setParameter ( "ProductID", request.getParameter ( "productName" ) );
            hold.setParameter ( "Year", year );
        }
        return hold;
    }

    public static Iterator getSelectedLineItems ( HttpServletRequest request ) throws ScalarException
    {
        String[] lineItemIds = request.getParameterValues ( "lineItemId" );
        ArrayList selected = new ArrayList ();

        for ( int i = 0; i < lineItemIds.length; i++ )
        {
            if ( request.getParameter ( "selected" + i ) != null )
            {
                selected.add ( lineItemIds[i] );
            }
        }
        return selected.iterator ();
    }

    public static Iterator getAllSelectedLineItems ( HttpServletRequest request ) throws ScalarException
    {
        String checkedCount = request.getParameter ( "bgCount" );
        String[] lineItemIds = request.getParameterValues ( "lineItemId" );
        String[] salesOrderIds = request.getParameterValues ( "salesOrderId" );
        String[] marketingHolds = request.getParameterValues ( "marketingHold" );
        String[] financeHolds = request.getParameterValues ( "financeHold" );
        String[] operationsHolds = request.getParameterValues ( "operationsHold" );
        String[] salesHolds = request.getParameterValues ( "salesHold" );
        String[] scheduleDates = request.getParameterValues ( "scheduleDate" );

        ArrayList selected = new ArrayList ();
        LineItem item = null;

        for ( int i = 0; i < lineItemIds.length; i++ )
        {

            if ( request.getParameter ( "selected" + i ) != null )
            {
                item = new LineItem ();
                item.setLineItemId ( Integer.parseInt ( lineItemIds[i] ) );
                item.setSalesOrderId ( Integer.parseInt ( salesOrderIds[i] ) );
                item.setScheduleDate ( scheduleDates[i] );

                if ( ( marketingHolds != null ) && ( marketingHolds[i] != null ) )
                {
                    item.setMarketingHold ( marketingHolds[i] );
                }
                else
                {
                    item.setMarketingHold ( null );
                }

                if ( ( salesHolds != null ) && ( salesHolds[i] != null ) )
                {
                    item.setSalesHold ( salesHolds[i] );
                }
                else
                {
                    item.setSalesHold ( null );
                }

                if ( ( operationsHolds != null ) && ( operationsHolds[i] != null ) )
                {
                    item.setOperationsHold ( operationsHolds[i] );
                }
                else
                {
                    item.setOperationsHold ( null );
                }

                if ( ( financeHolds != null ) && ( financeHolds[i] != null ) )
                {
                    item.setFinanceHold ( financeHolds[i] );
                }
                else
                {
                    item.setFinanceHold ( null );
                }
                selected.add ( item );
            }
        }
        return selected.iterator ();
    }


    public static ArrayList loadManufacturingProducts( int isSample ) throws Exception
    {
        ArrayList parts = new ArrayList ();
        Iterator list   = null;
        if( isSample == 0 )
        {
            list = FinishedGoodsDAO.loadFinishedGoods().iterator ();
        }
        else
        {
            list = FinishedGoodsDAO.loadAllFinishedGoods().iterator ();
        }
        parts.add ( new org.apache.struts.util.LabelValueBean ( "All Products", "" ) );
        while ( list.hasNext () )
        {
            FinishedGoods product = ( FinishedGoods ) list.next ();
            //It is better to replace with product Id here, instead of again searching the database with marketingpart no for productid
            //But i am leaving the other code as it is because we need to change lot of the code in the salesDAO. ;)
            parts.add ( new org.apache.struts.util.LabelValueBean ( product.getManufacturingPartNo (), product.getManufacturingPartNo () ) );
        }

        return parts;
    }
    //For sending the mail when the sales order is approved
    private void notifyApprovedSalesOrderInfo ( int salesOrderId )
    {
        SalesOrder salesOrder = null;

        String from = null;
        String to = null;
        String cc = null;
        String subject = null;
        String message = null;

        try
        {
            salesOrder = SalesOrderDAO.loadSalesOrder ( salesOrderId + "" );

            if ( SalesOrderDAO.isSalesOrderApproved ( salesOrder.getSalesOrderId () ) == true )
            {
                //from = "Chiptrac Admin <" + ConfigManager.getSysAdminEmail () + ">";
                from = ConfigManager.getFromEmailId(Constants.FROM_EMAIL_SALES_GROUP_NAME );
                to = salesOrder.getEnteredByName () + "<" + UserDAO.loadEmailByInternalUserId( null, salesOrder.getEnteredById () ) + ">";
                cc = StringUtils.concatStrings ( SalesOrderDAO.loadEmailListForApprovedSalesOrderNotification (), Mailer.EMAIL_SEPARATOR );

                //Send Notification mail to Customer Contact Person also
                /*if( salesOrder.getEmail() != null && salesOrder.getEmail().trim().length() > 0 )
                {
                    if( cc == null || cc.trim().length() == 0 )
                    {
                        cc = salesOrder.getEmail();
                    }
                    else
                    {
                        cc = cc + "," + salesOrder.getEmail();
                    }
                }*/
                String method = salesOrder.getShippingMethodName();
				String shippingMethod  = null ;
				if(method != null && method.trim().length()!= 0)
				{
					 shippingMethod = salesOrder.getShippingMethodName() +"#"+ salesOrder.getShippingAccount();
				}
				else
				{
					shippingMethod = "";
				}
                String shippingMethodLabel = null;
                try
                {
                    shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                    if ( shippingMethodLabel == null )
                    {
                        shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                }
                String endUserLabel = null;
                String endCustomerLabel = null;
                try
                {
                    endCustomerLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.endCustomer" );
                    if ( endCustomerLabel == null )
                    {
                        endCustomerLabel = Labels.DEFAULT_END_CUSTOMER_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    endCustomerLabel    = Labels.DEFAULT_END_CUSTOMER_LABEL;
                }
                try
                {
                    endUserLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.endUser" );
                    if ( endUserLabel == null )
                    {
                        endUserLabel = Labels.DEFAULT_END_USER_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    endUserLabel    = Labels.DEFAULT_END_USER_LABEL;
                }

                subject = "Sales Order " + salesOrder.getSalesOrderNo () + " has been approved";
                message = "<HTML><BODY><P><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>This is to notify that the sales order <b>" + salesOrder.getSalesOrderNo () + "</b> has been approved. </FONT><BR><BR><TABLE WIDTH=677 BORDER=0 CELLPADDING=4 CELLSPACING=0><TR BGCOLOR=\"#ccccff\"><TH COLSPAN=5 WIDTH=669 HEIGHT=30 VALIGN=CENTER><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Sales Order Information:</FONT></FONT></P></TH></TR>" +
                        "<TR BGCOLOR=\"#e6e6e6\"><TD WIDTH=136 VALIGN=TOP><P><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Sale Order No:</FONT></FONT></P></TD><TD WIDTH=167 VALIGN=BOTTOM SDVAL=\"10185\" SDNUM=\"1033;\"><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getSalesOrderNo () + "</FONT></FONT></P></TD><TD WIDTH=33 VALIGN=TOP><P><BR></P></TD><TD WIDTH=134 VALIGN=TOP><P><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Customer Name:</FONT></FONT></P></TD><TD WIDTH=167 VALIGN=TOP><P><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getCustomerName () + "</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Customer PO:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getCustomerPO () + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Contact Person:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getContactPerson () + "</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Phone No:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getPhoneNumber() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Cell No:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getCellNumber() +"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Fax :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getFaxNumber() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Email:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getEmail() +"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Sales Person:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getSalesPerson() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2></FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        // Added by veeru on 17th July 2004

                        "" +"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>"+shippingMethodLabel+" :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        shippingMethod+"</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2></FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        "" +"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Pay Terms :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getShippingTerms() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Delivery Terms:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getDeliveryTerms() +	"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Regional Rep :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getRegionalRep() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Booking Date:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getSalesOrderDate() +"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2> " + endUserLabel + " :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getEndCustomer() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2></FONT></FONT></P> " + endCustomerLabel + " :</TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getOdm() + "</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Billing Address :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getBillingAddress() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Shipping Address:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getShippingAddress() +"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Comments :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getComments() + 	"</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Shipping Instructions :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getShippingInstructions() + "</FONT></TD></TR></TABLE></BODY></HTML>";


                Mailer.send ( from,
                              to,
                              cc,
                              null /*bcc*/,
                              subject,
                              message,
                              null /*attachments*/,
                              Mailer.CONTENT_TYPE_HTML,
                              false /*Dont verify if the receipient is a ChipTrac user*/ );
            }
        }
        catch ( Exception e )
        {
            e.printStackTrace ();
            System.out.println ( "WARNING!! Could not notify " + to + " about the approved sales order: " + salesOrder.getSalesOrderNo () );
        }
    }

    private void notifyFinanceReasonCode ( int salesOrderId )
    {
        SalesOrder salesOrder = null;
        ArrayList lineItems = null;

        String from = null;
        String to = null;
        String cc = null;
        String subject = null;
        String message = null;

        try
        {
            salesOrder = SalesOrderDAO.loadSalesOrder ( salesOrderId + "" );
            if ( SalesOrderDAO.isSalesOrderApprovedButFinanceReasonCode ( salesOrder.getSalesOrderId () ) == true )
            {
                // Construct receipient list
                //from = "Chiptrac Admin <" + ConfigManager.getSysAdminEmail () + ">";
                from = ConfigManager.getFromEmailId(Constants.FROM_EMAIL_SALES_GROUP_NAME );
                to = salesOrder.getEnteredByName () + "<" + UserDAO.loadEmailByInternalUserId( null, salesOrder.getEnteredById () ) + ">";
                cc = StringUtils.concatStrings ( SalesOrderDAO.loadEmailListForApprovedSalesOrderNotification (), Mailer.EMAIL_SEPARATOR );

                //Send Notification mail to Customer Contact Person also
               /* if( salesOrder.getEmail() != null && salesOrder.getEmail().trim().length() > 0 )
                {
                    if( cc == null || cc.trim().length() == 0 )
                    {
                        cc = salesOrder.getEmail();
                    }
                    else
                    {
                        cc = cc + "," + salesOrder.getEmail();
                    }
                }*/
                String method = salesOrder.getShippingMethodName();
				String shippingMethod  = null ;
				if(method != null && method.trim().length()!= 0)
				{
					 shippingMethod = salesOrder.getShippingMethodName() +"#"+ salesOrder.getShippingAccount();
				}
				else
				{
					shippingMethod = "";
				}
                String shippingMethodLabel = null;
                try
                {
                    shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                    if ( shippingMethodLabel == null )
                    {
                        shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                }
                String endUserLabel = null;
                try
                {
                    endUserLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.endCustomer" );
                    if ( endUserLabel == null )
                    {
                        endUserLabel = Labels.DEFAULT_END_CUSTOMER_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    endUserLabel    = Labels.DEFAULT_END_CUSTOMER_LABEL;
                }
                subject = "All the holds except finance have been removed on the Sales Order " + salesOrder.getSalesOrderNo () + "";
                message = "<HTML><BODY><P><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>This is to notify that all the holds except for the finance have been removed on the sales order <b>" + salesOrder.getSalesOrderNo () + "</b> . </FONT><BR><BR><TABLE WIDTH=677 BORDER=0 CELLPADDING=4 CELLSPACING=0><TR BGCOLOR=\"#ccccff\"><TH COLSPAN=5 WIDTH=669 HEIGHT=30 VALIGN=CENTER><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Sales Order Information:</FONT></FONT></P></TH></TR>" +
                        "<TR BGCOLOR=\"#e6e6e6\"><TD WIDTH=136 VALIGN=TOP><P><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Sale Order No:</FONT></FONT></P></TD><TD WIDTH=167 VALIGN=BOTTOM SDVAL=\"10185\" SDNUM=\"1033;\"><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getSalesOrderNo () + "</FONT></FONT></P></TD><TD WIDTH=33 VALIGN=TOP><P><BR></P></TD><TD WIDTH=134 VALIGN=TOP><P><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Customer Name:</FONT></FONT></P></TD><TD WIDTH=167 VALIGN=TOP><P><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getCustomerName () + "</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Customer PO:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getCustomerPO () + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Contact Person:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getContactPerson () + "</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Phone No:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getPhoneNumber() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Cell No:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getCellNumber() +"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Fax :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getFaxNumber() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Email:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getEmail() +"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Sales Person:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getSalesPerson() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2></FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +

                        "" +"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>"+shippingMethodLabel+" :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        shippingMethod+"</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2></FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        "" +"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Pay Terms :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getShippingTerms() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Delivery Terms:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getDeliveryTerms() +	"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Regional Rep :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getRegionalRep() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Booking Date:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getSalesOrderDate() +"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>"+endUserLabel+" :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getOdm() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2></FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        ""+ "</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Billing Address :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getBillingAddress() + "</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Shipping Address:</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getShippingAddress() +"</FONT></FONT></P></TD></TR><TR BGCOLOR=\"#e6e6e6\" VALIGN=TOP><TD WIDTH=136><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Comments :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getComments() + 	"</FONT></FONT></P></TD><TD WIDTH=33><P ALIGN=LEFT><BR></P></TD><TD WIDTH=134><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>Shipping Instructions :</FONT></FONT></P></TD><TD WIDTH=167><P ALIGN=LEFT><FONT FACE=\"Verdana, sans-serif\"><FONT SIZE=2>" +
                        salesOrder.getShippingInstructions() + "</FONT></TD></TR></TABLE></BODY></HTML>";

                Mailer.send ( from,
                              to,
                              cc,
                              null /*bcc*/,
                              subject,
                              message,
                              null /*attachments*/,
                              Mailer.CONTENT_TYPE_HTML,
                              false /*Dont verify if the receipient is a ChipTrac user*/ );
            }
        }
        catch ( Exception e )
        {
            e.printStackTrace ();
            System.out.println ( "WARNING!! Could not notify " + to + " about the finance reason code for the  sales order: " + salesOrder.getSalesOrderNo () );
        }
    }

    //ArrayList list = null;
}
